package com.example.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blogapi.domain.MsSysUser;
import com.example.blogapi.mapper.MsSysUserMapper;
import com.example.blogapi.service.LoginService;
import com.example.blogapi.service.MsSysUserService;
import com.example.blogapi.service.TokenService;
import com.example.blogapi.utils.JWTUtils;
import com.example.blogapi.vo.ErrorCode;
import com.example.blogapi.vo.Result;
import com.example.blogapi.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* @author 13723
* @description 针对表【ms_sys_user】的数据库操作Service实现
* @createDate 2022-10-20 15:22:58
*/
@Service
public class MsSysUserServiceImpl extends ServiceImpl<MsSysUserMapper, MsSysUser>
implements MsSysUserService {
    @Autowired
    TokenService tokenService;
    @Autowired
    MsSysUserMapper msSysUserMapper;
    @Override
    public MsSysUser findUser(String account, String password) {
        LambdaQueryWrapper<MsSysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(MsSysUser::getAccount,MsSysUser::getId,MsSysUser::getAvatar,MsSysUser::getNickname);
        queryWrapper.eq(MsSysUser::getAccount,account).eq(MsSysUser::getPassword,password);
        MsSysUser user = getOne(queryWrapper);
        return user;
    }

    @Override
    public Result findUserByToken(String token) {
        MsSysUser user = tokenService.checkout(token);
        if (user == null){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMes());
        }
        return Result.success(user);
    }

    @Override
    public MsSysUser findUserByAccount(String account) {
        LambdaQueryWrapper<MsSysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MsSysUser::getAccount,account);
        return msSysUserMapper.selectOne(lambdaQueryWrapper);
    }

    public UserVo findUserVoById(Long userId){
        MsSysUser user = msSysUserMapper.selectById(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return userVo;
    }
    public boolean save(MsSysUser user){
        int i = msSysUserMapper.insert(user);
        if (i > 0){
            return true;
        } else {
            return false;
        }
    }
}
